export function ready(fn: () => void) {
    if (document.readyState !== 'loading') {
        fn();
    } else {
        document.addEventListener('DOMContentLoaded', fn);
    }
}

export function assert(condition: any, message?: string): asserts condition {
    if (!condition) {
        throw new Error(message || "Assertion failed");
    }
}

export function getApiPath(): string {
    return "/api" + window.location.pathname + window.location.search
}

export function sameDay(d1: Date, d2: Date) {
    return d1.getFullYear() === d2.getFullYear() &&
        d1.getMonth() === d2.getMonth() &&
        d1.getDate() === d2.getDate();
}

export function formatDateZhCn(date: string) {
    return new Date(date).toLocaleDateString("zh-cn", {
        year: "numeric",
        month: "short",
        day: "numeric",
    });
}

/**
 * From https://docs.djangoproject.com/en/5.1/howto/csrf/
 */
export function getCookie(name: string) {
    let cookieValue = null;
    if (document.cookie && document.cookie !== '') {
        const cookies = document.cookie.split(';');
        for (let i = 0; i < cookies.length; i++) {
            const cookie = cookies[i].trim();
            // Does this cookie string begin with the name we want?
            if (cookie.substring(0, name.length + 1) === (name + '=')) {
                cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
                break;
            }
        }
    }
    return cookieValue;
}

export function getCsrfToken() {
    return getCookie('csrftoken');
}


export interface ModalOptions {
    contentElem: HTMLElement;
    onClose?: () => void;
}

export function createModal({ contentElem, onClose }: ModalOptions): HTMLElement {
    const modalElem = document.getElementById("by6_modal_js")! as HTMLDialogElement;
    const modalBodyElem = modalElem.querySelector("#by6_modal_js_body")! as HTMLElement;
    modalBodyElem.replaceChildren(contentElem);

    const closeModalBtnElem = modalElem.querySelector("#by6_modal_js_close_btn")! as HTMLElement;
    closeModalBtnElem.addEventListener('click', () => {
        onClose?.();
    });

    modalElem.showModal();
    
    return modalElem;
}



export function resetHeaderLineHTMX() {
    const crumsRightElem = document.getElementById("headerline-crumbs-right") as HTMLElement;
    assert(crumsRightElem, `Cannot find element with id 'headerline-crumbs-right'`);
    crumsRightElem.innerHTML = ``;
    
    const crumbsElem = document.getElementById("headerline-crumbs") as HTMLElement;
    assert(crumsRightElem, `Cannot find element with id 'headerline-crumbs'`);
    crumbsElem.innerHTML = `
<div>
  <a class="by6-crumbs-action-btn" href="">
    <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="currentColor" class="tw:size-4">
      <path fill-rule="evenodd" d="M7.72 12.53a.75.75 0 0 1 0-1.06l7.5-7.5a.75.75 0 1 1 1.06 1.06L9.31 12l6.97 6.97a.75.75 0 1 1-1.06 1.06l-7.5-7.5Z" clip-rule="evenodd" />
    </svg>
  </a>
</div>
`;
}
